package com.zyl.blog.common.utils.Extreme;

import java.util.regex.Pattern;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.utils.Extreme
 * @ClassName: TextCleaner
 * @Description:
 * @Author FinalFantasy
 * @Date 2025/3/14-15:21
 */
public class TextCleaner {
    // 定义常见需要清理的字符模式
    private static final Pattern MULTI_NEWLINE = Pattern.compile("\n{2,}");
    private static final Pattern LEADING_TRAILING_SPACES = Pattern.compile("^\\s+|\\s+$");
    private static final Pattern SPECIAL_CHARS = Pattern.compile("[�♦★▪]+");
    private static final Pattern EXTRA_SPACES = Pattern.compile("\\s{2,}");
    private static final Pattern HTML_ENTITIES = Pattern.compile("&[a-z]+;");

    // 完整清理流程
    public static String cleanResponse(String rawText) {
        if (rawText == null || rawText.isEmpty()) {
            return rawText;
        }

        // 分步骤清理
        return rawText
                .replaceAll(MULTI_NEWLINE.pattern(), "\n")     // 合并多个换行
                .replaceAll(SPECIAL_CHARS.pattern(), "")       // 移除特殊符号
                .replaceAll(HTML_ENTITIES.pattern(), "")       // 去除HTML实体
                .replaceAll(LEADING_TRAILING_SPACES.pattern(), "") // 首尾空格
                .replaceAll(EXTRA_SPACES.pattern(), " ")       // 合并多个空格
                .replace("</s>", "")                           // 移除结束标记
                .trim();
    }

    // 带自定义规则的重载方法
    public static String cleanResponse(String rawText, Pattern... customPatterns) {
        String cleaned = cleanResponse(rawText);
        for (Pattern p : customPatterns) {
            cleaned = p.matcher(cleaned).replaceAll("");
        }
        return cleaned;
    }
}